package utils

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
)

// serverUrl swagger服务地址
var serverUrl = [4]string{
	"http://172.16.0.106/operation-manager/v2/api-docs",
	"http://172.16.0.106/scheduling/v2/api-docs",
	"http://172.16.0.106/uc/v2/api-docs",
	"http://172.16.0.106/portal/v2/api-docs",
}

// GetDoc 读取接口文档
func GetDoc() map[string]map[string]string {
	newPathMap := make(map[string]map[string]string)
	for _, v := range serverUrl {
		getSwaggerDoc(v, newPathMap)
	}
	return newPathMap
}

//读取swagger接口
func getSwaggerDoc(url string, newPathMap map[string]map[string]string) {
	//生成client 参数为默认
	client := &http.Client{}

	//提交请求
	request, err := http.NewRequest("GET", url, nil)

	if err != nil {
		panic(err)
	}

	//处理返回结果
	response, _ := client.Do(request)
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Printf("调用失败:%v\n", err)
	}
	context := string(body)
	contextMap := make(map[string]map[string]map[string]map[string]string)
	//字符串转json
	err = json.Unmarshal([]byte(context), &contextMap)
	if err != nil {
		fmt.Printf("解析失败 %v\n", err)
	}

	pathMap := contextMap["paths"]

	for k, v := range pathMap {
		m := v
		for kk, vv := range m {
			docMap := make(map[string]string)
			docMap["name"] = vv["summary"]
			docMap["method"] = strings.ToUpper(kk)
			newPathMap[k] = docMap
		}
	}
}
